package cn.ug.pay.web.controller;

import cn.ug.account.bean.DataDictionaryBean;
import cn.ug.bean.LoginBean;
import cn.ug.bean.base.SerializeObject;
import cn.ug.bean.type.ResultType;
import cn.ug.config.FundRateConfig;
import cn.ug.config.YeePayConfig;
import cn.ug.core.SerializeObjectError;
import cn.ug.core.ensure.Ensure;
import cn.ug.core.login.LoginHelper;
import cn.ug.enums.RateKeyEnum;
import cn.ug.feign.*;
import cn.ug.mall.bean.FeeBean;
import cn.ug.mall.bean.GoodsSkuBean;
import cn.ug.member.bean.AddressBean;
import cn.ug.member.bean.request.MemberUserBaseParmBean;
import cn.ug.member.bean.response.MemberUserBean;
import cn.ug.member.mq.MemberPasswordStatusMQ;
import cn.ug.mq.DelayMessagePostProcessor;
import cn.ug.pay.bean.request.PayParamBean;
import cn.ug.pay.bean.request.RechargeParamBean;
import cn.ug.pay.bean.request.YeePayParamBean;
import cn.ug.pay.bean.status.CommonConstants;
import cn.ug.pay.mapper.entity.Trade;
import cn.ug.pay.pay.yeepay.TZTService;
import cn.ug.pay.service.BankCardService;
import cn.ug.pay.service.BillService;
import cn.ug.pay.service.MemberGoldService;
import cn.ug.pay.service.TradeService;
import cn.ug.pay.utils.DigestUtil;
import cn.ug.pay.utils.RequestUtil;
import cn.ug.util.Common;
import cn.ug.util.SerialNumberWorker;
import cn.ug.util.UF;
import cn.ug.web.controller.BaseController;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.ug.util.ConstantUtil.GBK;

import static cn.ug.config.QueueName.QUEUE_MEMBER_PASSWORD_STATUS_DELAY;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

@RestController
@RequestMapping("trade")
public class TradeController extends BaseController {
    @Autowired
    private RateSettingsService rateSettingsService;
    @Resource
    private AmqpTemplate amqpTemplate;
    @Resource
    private TradeService tradeService;
    @Autowired
    private MemberAddressService memberAddressService;
    @Autowired
    private BankCardService bankCardService;
    @Autowired
    private MemberUserService memberUserService;
    @Autowired
    private MemberGoldService memberGoldService;
    @Autowired
    private GoodsService goodsService;
    @Resource
    private RequestUtil requestUtil;
    @Resource
    private TZTService tZTService;
    @Autowired
    private BillService billService;
    @Autowired
    private FundRateConfig fundRateConfig;
    @Resource
    private YeePayConfig yeePayConfig;
    @Value("${yeepay.ebank.merchantId}")
    private String merchantId;
    @Value("${yeepay.ebank.hmacKey}")
    private String hmacKey;
    @Value("${yeepay.ebank.payUrl}")
    private String payUrl;

    @Autowired
    private DataDictionaryService dataDictionaryService;

    private static Logger logger = LoggerFactory.getLogger(TradeController.class);

    @GetMapping("/mine/show")
    public SerializeObject showMineView() {
        SerializeObject<List<DataDictionaryBean>> beans = dataDictionaryService.findListByClassification("APP_ROOTLE_MINE_SHOW", 1);
        int value = 1;
        String url = "";
        JSONObject result = new JSONObject();
        if (beans != null && beans.getData() != null && beans.getData().size() > 0) {
            value = Integer.parseInt(beans.getData().get(0).getItemValue());
            url = beans.getData().get(0).getDescription();
        }
        result.put("show", value);
        result.put("url", url);
        return new SerializeObject(ResultType.NORMAL, "", result);
    }

    @GetMapping("/show")
    public SerializeObject show(HttpServletRequest httpServletRequest) {
        String version = httpServletRequest.getHeader("app");
        logger.info("客户端当前版本号===" + version);
        SerializeObject rateBean = rateSettingsService.get("appVersion");
        if (rateBean != null && rateBean.getData() != null) {
            JSONObject json = JSON.parseObject(JSONObject.toJSONString(rateBean.getData()));
            String appVersions = json.get("appVersions").toString();
            if (StringUtils.isNotBlank(appVersions) && appVersions.contains(version)) {
                return new SerializeObject(ResultType.NORMAL, "", 0);
            }
        }
        SerializeObject<List<DataDictionaryBean>> beans = dataDictionaryService.findListByClassification("APP_VIEW_SHOW", 1);
        int value = 1;
        if (beans != null && beans.getData() != null && beans.getData().size() > 0) {
            value = Integer.parseInt(beans.getData().get(0).getItemValue());
        }

        return new SerializeObject(ResultType.NORMAL, "", value);
    }

    @RequestMapping(value = "/ebank/recharge", method = POST)
    public SerializeObject recharge(@RequestHeader String accessToken, BigDecimal amount, String returnUrl) {
        LoginBean loginBean = LoginHelper.getLoginBean();
        if (loginBean == null || StringUtils.isBlank(loginBean.getId())) {
            Ensure.that(0).isLt(1, "00000102");
        }
        SerializeObject rateBean = rateSettingsService.get(RateKeyEnum.RECHARGE.getKey());
        BigDecimal fee = BigDecimal.ZERO;
        if (rateBean != null && rateBean.getData() != null) {
            JSONObject json = JSON.parseObject(JSONObject.toJSONString(rateBean.getData()));
            BigDecimal minAmount = json.getBigDecimal("minAmount");
            if (amount == null || (minAmount != null && amount.compareTo(minAmount) < 0)) {
                Ensure.that(0).isLt(1, "17002040");
            }
            int dayNum = billService.getTransactionNumForThisDay(loginBean.getId(), CommonConstants.PayType.RECHARGE.getIndex());
            int monthNum = billService.getTransactionNumForThisMonth(loginBean.getId(), CommonConstants.PayType.RECHARGE.getIndex());
            fee = fundRateConfig.getFee(json, amount, dayNum, monthNum);
        }
        BigDecimal totalAmount = amount.add(fee);
        //业务类型
        String p0Cmd = "Buy";
        //商户编号
        String p1MerId = merchantId;
        //商户订单号
        String p2Order = SerialNumberWorker.getInstance().nextId();
        //支付金额
        String p3Amt = String.valueOf(totalAmount);
        //交易币种
        String p4Cur = "CNY";
        //商品名称
        String p5Pid = "ugold";
        String p6Pcat = "";
        String p7Pdesc = "";
        //回调地址
        String p8Url = returnUrl;
        String p9SAF = "";
        String paMP = "";
        String pbServerNotifyUrl = StringUtils.replace(yeePayConfig.getRechargeCallBackUrl(), "yeePayRechargeAsyNotify", "ebank/recharge/notify");
        String pdFrpId = "";
        String pmPeriod = "";
        String pnUnit = "";
        String prNeedResponse = "1";
        String ptUserName = "";
        String ptPostalCode = "";
        String ptAddress = "";
        String ptTeleNo = "";
        String ptMobile = "";
        String ptEmail = "";
        String ptLeaveMessage = "";
        String keyValue = hmacKey;

        String[] strArr = new String[]{p0Cmd, p1MerId, p2Order, p3Amt, p4Cur, p5Pid, p6Pcat, p7Pdesc,
                p8Url, p9SAF, paMP, pbServerNotifyUrl, pdFrpId, pmPeriod, pnUnit, prNeedResponse,
                ptUserName, ptPostalCode, ptAddress, ptTeleNo, ptMobile, ptEmail, ptLeaveMessage};
        String hmac = DigestUtil.getHmac(strArr, keyValue);
        try {
            p0Cmd = URLEncoder.encode(p0Cmd, GBK);
            p1MerId = URLEncoder.encode(p1MerId, GBK);
            p2Order = URLEncoder.encode(p2Order, GBK);
            p3Amt = URLEncoder.encode(p3Amt, GBK);
            p4Cur = URLEncoder.encode(p4Cur, GBK);
            p5Pid = URLEncoder.encode(p5Pid, GBK);
            p6Pcat = URLEncoder.encode(p6Pcat, GBK);
            p7Pdesc = URLEncoder.encode(p7Pdesc, GBK);
            p8Url = URLEncoder.encode(p8Url, GBK);
            p9SAF = URLEncoder.encode(p9SAF, GBK);
            paMP = URLEncoder.encode(paMP, GBK);
            pbServerNotifyUrl = URLEncoder.encode(pbServerNotifyUrl, GBK);
            pdFrpId = URLEncoder.encode(pdFrpId, GBK);
            pmPeriod = URLEncoder.encode(pmPeriod, GBK);
            pnUnit = URLEncoder.encode(pnUnit, GBK);
            prNeedResponse = URLEncoder.encode(prNeedResponse, GBK);
            ptUserName = URLEncoder.encode(ptUserName, GBK);
            ptPostalCode = URLEncoder.encode(ptPostalCode, GBK);
            ptAddress = URLEncoder.encode(ptAddress, GBK);
            ptTeleNo = URLEncoder.encode(ptTeleNo, GBK);
            ptMobile = URLEncoder.encode(ptMobile, GBK);
            ptEmail = URLEncoder.encode(ptEmail, GBK);
            ptLeaveMessage = URLEncoder.encode(ptLeaveMessage, GBK);
            hmac = URLEncoder.encode(hmac, GBK);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Trade trade = new Trade();
        trade.setId(UF.getRandomUUID());
        trade.setMemberId(loginBean.getId());
        trade.setOrderId(p2Order);
        trade.setSerialNumber(p2Order);
        trade.setTitle(CommonConstants.RECHARGE);
        trade.setStatus(CommonConstants.PayStatus.NEW.getIndex());
        trade.setPayWay(CommonConstants.PayWay.YEE_PAY.getIndex());
        trade.setType(CommonConstants.PayType.RECHARGE.getIndex());
        trade.setAmount(amount);
        trade.setPayAmount(totalAmount);
        trade.setFee(fee);
        tradeService.save(trade);

        String requestURL = payUrl;
        StringBuffer payURL = new StringBuffer();

        payURL.append(requestURL).append("?");
        payURL.append("p0_Cmd=").append(p0Cmd);
        payURL.append("&p1_MerId=").append(p1MerId);
        payURL.append("&p2_Order=").append(p2Order);
        payURL.append("&p3_Amt=").append(p3Amt);
        payURL.append("&p4_Cur=").append(p4Cur);
        payURL.append("&p5_Pid=").append(p5Pid);
        payURL.append("&p6_Pcat=").append(p6Pcat);
        payURL.append("&p7_Pdesc=").append(p7Pdesc);
        payURL.append("&p8_Url=").append(p8Url);
        payURL.append("&p9_SAF=").append(p9SAF);
        payURL.append("&pa_MP=").append(paMP);
        payURL.append("&pb_ServerNotifyUrl=").append(pbServerNotifyUrl);
        payURL.append("&pd_FrpId=").append(pdFrpId);
        payURL.append("&pm_Period=").append(pmPeriod);
        payURL.append("&pn_Unit=").append(pnUnit);
        payURL.append("&pr_NeedResponse=").append(prNeedResponse);
        payURL.append("&pt_UserName=").append(ptUserName);
        payURL.append("&pt_PostalCode=").append(ptPostalCode);
        payURL.append("&pt_Address=").append(ptAddress);
        payURL.append("&pt_TeleNo=").append(ptTeleNo);
        payURL.append("&pt_Mobile=").append(ptMobile);
        payURL.append("&pt_Email=").append(ptEmail);
        payURL.append("&pt_LeaveMessage=").append(ptLeaveMessage);
        payURL.append("&hmac=").append(hmac);
        return new SerializeObject(ResultType.NORMAL, "", payURL.toString());
    }

    @RequestMapping(value = "/ebank/recharge/notify")
    public String notify(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        request.setCharacterEncoding(GBK);
        String p1MerId = formatString(request.getParameter("p1_MerId"));
        String r0Cmd = formatString(request.getParameter("r0_Cmd"));
        String r1Code = formatString(request.getParameter("r1_Code"));
        String r2TrxId = formatString(request.getParameter("r2_TrxId"));
        String r3Amt = formatString(request.getParameter("r3_Amt"));
        String r4Cur = formatString(request.getParameter("r4_Cur"));
        String r5Pid = formatString(request.getParameter("r5_Pid"));
        String r6Order = formatString(request.getParameter("r6_Order"));
        String r7Uid = formatString(request.getParameter("r7_Uid"));
        String r8MP = formatString(request.getParameter("r8_MP"));
        String r9BType = formatString(request.getParameter("r9_BType"));
        String hmac = formatString(request.getParameter("hmac"));
        String hmacSafe = formatString(request.getParameter("hmac_safe"));

        String[] strArr = {p1MerId, r0Cmd, r1Code, r2TrxId, r3Amt, r4Cur, r5Pid, r6Order, r7Uid, r8MP, r9BType};

        boolean hmacIsCorrect = verifyCallbackHmac(strArr, hmac);
        boolean hmacsafeIsCorrect = verifyCallbackHmacSafe(strArr, hmacSafe);
        getLog().info("网银充值异步回调参数=" + strArr[0] + "  " + strArr[1] + "  " + strArr[2] + "  " + strArr[3] + "  " + strArr[4] + "  " + strArr[5] + "  " + strArr[6] + "  " + strArr[7] + "  " + strArr[8] + "  " + strArr[9] + "  " + strArr[10]);
        getLog().info("网银充值异步回调参数验证：hmacIsCorrect=" + hmacIsCorrect + "&&&&hmacsafeIsCorrect=" + hmacsafeIsCorrect);

        if (hmacIsCorrect && hmacsafeIsCorrect && r9BType.equals("2")) {
            getLog().info("服务器回调~~~~~~~~~~SUCCESS~~~~~~~~~~~");
            if (tradeService.notifyForSuccess(r6Order, r2TrxId)) {
                return "SUCCESS";
            }
        }
        return "";
    }

    /*@RequestMapping(value = "refund" ,method = POST)
    public void refund(String orderNO, double amount) {
        TreeMap<String, String> dataMap	= new TreeMap<String, String>();
        dataMap.put("merchantno",   yeePayConfig.getMerchantAccount());
        dataMap.put("requestno",    UF.getRandomUU+
        -+
        -ID());
        dataMap.put("paymentyborderid", 	  orderNO);
        dataMap.put("amount", 	      String.valueOf(amount));
        dataMap.put("requesttime",  UF.getFormatDateTime(LocalDateTime.now()));
        dataMap.put("sign",          tZTService.getSign(dataMap));
        getLog().info("---充值退款请求参数---" + dataMap.toString());
        //发起请求
        Map<String, String> map = requestUtil.sendYeePayHttp("https://jinrong.yeepay.com/tzt-api/api/refund/request", dataMap);
        getLog().info("----支付退款结果：----" + map);
    }*/

    @RequestMapping(value = "recharge", method = POST)
    public SerializeObject recharge(@RequestHeader String accessToken, RechargeParamBean entity) {
        Map<String, String> map = new HashMap<String, String>();
        //验证参数--不为空
        Ensure.that(entity.getPayWay()).isNull("17000401");
        Ensure.that(entity.getAmount()).isNull("17000402");
        Ensure.that(entity.getPayPassword()).isNull("17000404");

        //验证参数--参数类型以及输入参数合法性
        //Ensure.that(entity.getAmount().compareTo(BigDecimal.valueOf(2)) < 0).isTrue("17000107");  //提现金额必须大于2元      //验证充值金额是否是正整数
        Ensure.that(CommonConstants.PayWay.getName(entity.getPayWay())).isNull("17000406"); //验证输入的支付方式是否正确
        Ensure.that(Common.isNumeric(entity.getPayPassword() + "")).isFalse("17000407"); //验证交易密码是否是数字
        Ensure.that(entity.getPayPassword().length() == 6).isFalse("17000408");  //验证交易密码长度是否正确

        LoginBean loginBean = LoginHelper.getLoginBean();
        Ensure.that(loginBean == null).isTrue("00000102");
        //验证交易密码是否正确
        // 交易密码验证
        SerializeObject obj = memberUserService.validatePayPassword(loginBean.getId(), entity.getPayPassword());
        if (null == obj || obj.getCode() != ResultType.NORMAL) {
            SerializeObject paramBean = rateSettingsService.get(RateKeyEnum.TRADE_PASSWORD.getKey());
            if (paramBean != null && paramBean.getData() != null) {
                JSONObject json = JSON.parseObject(JSONObject.toJSONString(paramBean.getData()));
                int isLimited = json.getIntValue("isLimited");
                int wrongTimes = json.getIntValue("wrongTimes");
                int minutes = json.getIntValue("minutes");
                if (isLimited == 1) {
                    SerializeObject<MemberUserBean> memberBean = memberUserService.findById(loginBean.getId());
                    if (null == memberBean || memberBean.getData() == null) {
                        return new SerializeObjectError("00000102");
                    }
                    MemberUserBean memberUserBean = memberBean.getData();
                    if (isLimited == 1 && memberUserBean.getTrdpassdStatus() == 1) {
                        SerializeObjectError result = new SerializeObjectError<>("17002034");
                        String msg = String.format(result.getMsg(), wrongTimes, minutes);
                        result.setMsg(msg);
                        return result;
                    }
                    int actualWrongTimes = memberUserBean.getTrdpassdWrongTimes();
                    actualWrongTimes++;
                    int status = 0;
                    if (wrongTimes <= actualWrongTimes) {
                        status = 1;
                    }
                    memberUserService.modifyWrongTimes(memberUserBean.getId(), 2, actualWrongTimes, status);
                    if (wrongTimes <= actualWrongTimes) {
                        MemberPasswordStatusMQ mq = new MemberPasswordStatusMQ();
                        mq.setMemberId(memberUserBean.getId());
                        mq.setType(2);
                        amqpTemplate.convertAndSend(QUEUE_MEMBER_PASSWORD_STATUS_DELAY, mq, new DelayMessagePostProcessor(minutes * 60 * 1000));

                        SerializeObjectError result = new SerializeObjectError<>("17002034");
                        String msg = String.format(result.getMsg(), wrongTimes, minutes);
                        result.setMsg(msg);
                        return result;
                    }
                }
            }
            return new SerializeObjectError<>("17000409");
        }
        memberUserService.modifyWrongTimes(loginBean.getId(), 2, 0, 0);
        String orderId = tradeService.recharge(entity);
        map.put("orderId", orderId);
        return new SerializeObject(ResultType.NORMAL, map);
    }

    /**
     * 充值--易宝易步回调(移动端)
     *
     * @param yeePayParamBean 易宝支付返回参数
     * @return 是否操作成功
     */
    @RequestMapping(value = "yeePayRechargeAsyNotify", method = POST)
    public void yeePayRechargeAsyNotify(HttpServletResponse httpServletResponse, YeePayParamBean yeePayParamBean) {
        String responseContent = tradeService.yeePayRechargeAsyNotify(yeePayParamBean);
        try {
            httpServletResponse.getWriter().append(responseContent);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 提金/换金接口
     */
    @PostMapping("/pay/with/gold")
    public SerializeObject userGold(@RequestHeader String accessToken, long skuId, int quantity, String payPassword,
                                    int type, long addressId, int source) {
        LoginBean loginBean = LoginHelper.getLoginBean();
        if (loginBean == null || StringUtils.isBlank(loginBean.getId())) {
            return new SerializeObjectError("00000102");
        }
        if (quantity <= 0) {
            return new SerializeObjectError("00000102");
        }
        String memberId = loginBean.getId();
        String cellphone = loginBean.getLoginName();
        if (addressId < 1) {
            return new SerializeObjectError("00000002");
        }
        SerializeObject<GoodsSkuBean> skuBean = goodsService.getSku(skuId);
        if (skuBean == null || skuBean.getData() == null) {
            return new SerializeObjectError("00000002");
        }
        int num = bankCardService.validateBindBankCard(memberId);
        if (num == 0) {
            return new SerializeObjectError("17002020");
        }
        SerializeObject<AddressBean> addressBean = memberAddressService.getAddress(addressId);
        if (null == addressBean || addressBean.getCode() != ResultType.NORMAL || null == addressBean.getData() || !StringUtils.equals(addressBean.getData().getUserId(), memberId)) {
            return new SerializeObjectError("00000102");
        }
        SerializeObject obj = memberUserService.validatePayPassword(memberId, payPassword);
        if (null == obj || obj.getCode() != ResultType.NORMAL) {
            info("交易密码验证失败。 memberId = " + memberId);
            SerializeObject paramBean = rateSettingsService.get(RateKeyEnum.TRADE_PASSWORD.getKey());
            if (paramBean != null && paramBean.getData() != null) {
                JSONObject json = JSON.parseObject(JSONObject.toJSONString(paramBean.getData()));
                int isLimited = json.getIntValue("isLimited");
                int wrongTimes = json.getIntValue("wrongTimes");
                int minutes = json.getIntValue("minutes");
                if (isLimited == 1) {
                    SerializeObject<MemberUserBean> memberBean = memberUserService.findById(memberId);
                    if (null == memberBean || memberBean.getData() == null) {
                        return new SerializeObjectError("00000102");
                    }
                    MemberUserBean memberUserBean = memberBean.getData();
                    if (isLimited == 1 && memberUserBean.getTrdpassdStatus() == 1) {
                        SerializeObjectError result = new SerializeObjectError<>("17002034");
                        String msg = String.format(result.getMsg(), wrongTimes, minutes);
                        result.setMsg(msg);
                        return result;
                    }
                    int actualWrongTimes = memberUserBean.getTrdpassdWrongTimes();
                    actualWrongTimes++;
                    int status = 0;
                    if (wrongTimes <= actualWrongTimes) {
                        status = 1;
                    }
                    memberUserService.modifyWrongTimes(memberUserBean.getId(), 2, actualWrongTimes, status);
                    if (wrongTimes <= actualWrongTimes) {
                        MemberPasswordStatusMQ mq = new MemberPasswordStatusMQ();
                        mq.setMemberId(memberUserBean.getId());
                        mq.setType(2);
                        amqpTemplate.convertAndSend(QUEUE_MEMBER_PASSWORD_STATUS_DELAY, mq, new DelayMessagePostProcessor(minutes * 60 * 1000));

                        SerializeObjectError result = new SerializeObjectError<>("17002034");
                        String msg = String.format(result.getMsg(), wrongTimes, minutes);
                        result.setMsg(msg);
                        return result;
                    }
                }
            }
            return obj;
        }
        memberUserService.modifyWrongTimes(memberId, 2, 0, 0);
        SerializeObject serializeObject = goodsService.validate(skuId, quantity, memberId, type);
        if (serializeObject != null && serializeObject.getCode() == ResultType.NORMAL) {
            SerializeObject<FeeBean> feeBean = goodsService.getFee(skuId, quantity, type);
            if (feeBean == null || feeBean.getData() == null) {
                return new SerializeObjectError("00000102");
            }
            FeeBean fee = feeBean.getData();

            return tradeService.pay(memberId, skuBean.getData(), quantity, type, addressId, fee, cellphone, source);
        } else {
            return serializeObject;
        }
    }

    /**
     * 公共支付--移动端
     *
     * @param payParamBean
     * @return
     */
    @RequestMapping(value = "commonPayRequest", method = POST)
    public SerializeObject commonPayRequest(@RequestHeader String accessToken, PayParamBean payParamBean) {
        Ensure.that(payParamBean.getOrderId()).isNull("17000413");
        Ensure.that(payParamBean.getType()).isNull("17000414");
        Ensure.that(payParamBean.getWay()).isNull("17000401");
        Ensure.that(payParamBean.getPayPassword()).isNull("17000404");
        Ensure.that(CommonConstants.PayWay.getName(payParamBean.getWay())).isNull("17000406");
        Ensure.that(payParamBean.getPayPassword().length() == 6).isFalse("17000408");  //验证交易密码长度是否正确
        LoginBean loginBean = LoginHelper.getLoginBean();
        Ensure.that(loginBean == null).isTrue("00000102");
        if (loginBean == null || StringUtils.isBlank(loginBean.getAccessToken()) || !StringUtils.equals(accessToken, loginBean.getAccessToken())) {
            return new SerializeObject<>(ResultType.UNLOGIN, "00000102");
        }
        //验证交易密码是否正确
        // 交易密码验证
        SerializeObject obj = memberUserService.validatePayPassword(loginBean.getId(), payParamBean.getPayPassword());
        if (null == obj || obj.getCode() != ResultType.NORMAL) {
            SerializeObject paramBean = rateSettingsService.get(RateKeyEnum.TRADE_PASSWORD.getKey());
            if (paramBean != null && paramBean.getData() != null) {
                JSONObject json = JSON.parseObject(JSONObject.toJSONString(paramBean.getData()));
                int isLimited = json.getIntValue("isLimited");
                int wrongTimes = json.getIntValue("wrongTimes");
                int minutes = json.getIntValue("minutes");
                if (isLimited == 1) {
                    SerializeObject<MemberUserBean> memberBean = memberUserService.findById(loginBean.getId());
                    if (null == memberBean || memberBean.getData() == null) {
                        return new SerializeObjectError("00000102");
                    }
                    MemberUserBean memberUserBean = memberBean.getData();
                    if (isLimited == 1 && memberUserBean.getTrdpassdStatus() == 1) {
                        SerializeObjectError result = new SerializeObjectError<>("17002034");
                        String msg = String.format(result.getMsg(), wrongTimes, minutes);
                        result.setMsg(msg);
                        return result;
                    }
                    int actualWrongTimes = memberUserBean.getTrdpassdWrongTimes();
                    actualWrongTimes++;
                    int status = 0;
                    if (wrongTimes <= actualWrongTimes) {
                        status = 1;
                    }
                    memberUserService.modifyWrongTimes(memberUserBean.getId(), 2, actualWrongTimes, status);
                    if (wrongTimes <= actualWrongTimes) {
                        MemberPasswordStatusMQ mq = new MemberPasswordStatusMQ();
                        mq.setMemberId(memberUserBean.getId());
                        mq.setType(2);
                        amqpTemplate.convertAndSend(QUEUE_MEMBER_PASSWORD_STATUS_DELAY, mq, new DelayMessagePostProcessor(minutes * 60 * 1000));

                        SerializeObjectError result = new SerializeObjectError<>("17002034");
                        String msg = String.format(result.getMsg(), wrongTimes, minutes);
                        result.setMsg(msg);
                        return result;
                    }
                }
            }
            return new SerializeObjectError<>("17000409");
        }
        memberUserService.modifyWrongTimes(loginBean.getId(), 2, 0, 0);
        Map<String, Object> resultMap = tradeService.commonPayRequest(payParamBean);
        //此处处理逻辑 ---保障整个事务数据插入到数据库中不会因为抛出异常导致无法插入到数据库
        if (resultMap != null && !resultMap.isEmpty()) {
            return new SerializeObject(ResultType.ERROR, resultMap.get("msg") + "");
        } else {
            return new SerializeObject(ResultType.NORMAL, "00000001");
        }
    }

    /**
     * 公共支付--易宝易步回调(移动端)
     *
     * @param yeePayParamBean 易宝支付返回参数
     * @return 是否操作成功
     */
    @RequestMapping(value = "yeePayAsyNotify", method = POST)
    public void yeePayAsyNotify(HttpServletResponse httpServletResponse, YeePayParamBean yeePayParamBean) {
        String responseContent = tradeService.yeePayAsyNotify(yeePayParamBean);
        try {
            httpServletResponse.getWriter().append(responseContent);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 提现--易宝易步回调(移动端)
     *
     * @param yeePayParamBean 易宝提现返回参数
     * @return 是否操作成功
     */
    @RequestMapping(value = "yeePayWithdrawAsyNotify", method = POST)
    public void yeePayWithdrawAsyNotify(HttpServletResponse httpServletResponse, YeePayParamBean yeePayParamBean) {
        String responseContent = tradeService.yeePayWithdrawAsyNotify(yeePayParamBean);
        try {
            httpServletResponse.getWriter().append(responseContent);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据订单号查询订单状态
     *
     * @param accessToken
     * @param orderId
     * @return
     */
    @GetMapping(value = "queryOrderStatus")
    public SerializeObject queryOrderStatus(@RequestHeader String accessToken, String orderId) {
        Map<String, String> resultMap = tradeService.queryOrderStatus(orderId);
        return new SerializeObject(ResultType.NORMAL, resultMap);
    }

    @RequestMapping(value = "test", method = POST)
    public SerializeObject test(@RequestHeader String accessToken, MemberUserBaseParmBean muParamBean) {
        /*memberUserService.updateBaseInfo(muParamBean);*/
        return new SerializeObject();
    }

    public boolean verifyCallbackHmacSafe(String[] stringValue, String hmacSafeFromYeepay) throws UnsupportedEncodingException {
        String keyValue = hmacKey;
        StringBuffer sourceData = new StringBuffer();
        for (int i = 0; i < stringValue.length; i++) {
            if (!"".equals(stringValue[i])) {
                sourceData.append(stringValue[i] + "#");
            }
        }
        sourceData = sourceData.deleteCharAt(sourceData.length() - 1);
        String localHmacSafe = DigestUtil.hmacSign(sourceData.toString(), keyValue);
        StringBuffer hmacSource = new StringBuffer();
        for (int i = 0; i < stringValue.length; i++) {
            hmacSource.append(stringValue[i]);
        }
        return (localHmacSafe.equals(hmacSafeFromYeepay) ? true : false);
    }

    public boolean verifyCallbackHmac(String[] stringValue, String hmacFromYeepay) throws UnsupportedEncodingException {
        String keyValue = hmacKey;
        StringBuffer sourceData = new StringBuffer();
        for (int i = 0; i < stringValue.length; i++) {
            stringValue[i] = URLDecoder.decode(stringValue[i], "GBK");
            stringValue[i] = new String(stringValue[i].getBytes("8859_1"), "GB2312");
            sourceData.append(stringValue[i]);
        }
        String localHmac = DigestUtil.getHmac(stringValue, keyValue);
        StringBuffer hmacSource = new StringBuffer();
        for (int i = 0; i < stringValue.length; i++) {
            hmacSource.append(stringValue[i]);
        }
        return (localHmac.equals(hmacFromYeepay) ? true : false);
    }

    private String formatString(String text) {
        return (text == null) ? "" : text.trim();
    }
}
